package com.ujiuye.web;

import com.ujiuye.entity.Student;
import com.ujiuye.service.StudentService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;

@MultipartConfig
@WebServlet("/addStu")
public class AddStuServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter pw = resp.getWriter();
        //获取上传的图片名
        Part part = req.getPart("spic");
        String filename = part.getSubmittedFileName();
        //重命名图片名
        filename = UUID.randomUUID()+filename;
        //设置上传路径
        String path="e:/pic";
        //获取表单数据-->存到map中
        Map<String, String[]> map = req.getParameterMap();
        Student s = new Student();
        //调用BeanUtils中映射方法将map中的数据映射到对象中
        try {
            BeanUtils.populate(s,map);
            System.out.println(s);
            //调用service中的添加方法
            StudentService ss = new StudentService();
            //在添加之前给spic属性赋值
            s.setSpic(filename);
            boolean flag = ss.addStu(s);
            if(flag){
                //添加成功-->显示学生信息
                //上传图片
                File f = new File(path);
                //如果路径不存在则创建
                if(!f.exists()){
                    f.mkdir();
                }
                //上传
                part.write(path+File.separator+filename);
                resp.sendRedirect("queryStuByPage");
            }else{
                pw.println("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
